#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// 全局变量
pthread_mutex_t mutex;
pthread_cond_t cond;
int ready = 0;

// 线程函数
void* thread_func(void* arg) {
    // 加锁
    pthread_mutex_lock(&mutex);

    // 等待条件变量变为ready
    while (!ready) {
        pthread_cond_wait(&cond, &mutex);
    }

    printf("Thread %ld is now running.\n", (long)arg);

    // 解锁
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main(void) {
    pthread_t thread1, thread2;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_create(&thread1, NULL, thread_func, (void*)1);
    pthread_create(&thread2, NULL, thread_func, (void*)2);

    sleep(2); // 等待一段时间

    // 加锁
    pthread_mutex_lock(&mutex);

    // 更改条件并唤醒所有等待线程
    ready = 1;
    pthread_cond_broadcast(&cond);

    // 解锁
    pthread_mutex_unlock(&mutex);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);

    return 0;
}